﻿using System;
using System.IO;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Xml;
using System.Xml.Linq;
using TS3ServerManager.BL;
using TS3ServerManager.BL.Eventing;
using TS3ServerManager.Windows;

namespace TS3ServerManager.Controls
{
    /// <summary>
    /// Interaction logic for ConnectionArea.xaml
    /// </summary>
    public partial class ConnectionAreaControl
    {
        public event EventHandler<ConnectEventArgs> StartConnection;

        public ConnectionAreaControl()
        {
            InitializeComponent();

            if (!IsInDesignMode)
            {
                Loaded += ConnectionAreaControl_Loaded;
                Application.Exit += Application_Exit;
            }
        }

        public void ReportConnectionState(ConnectionState connectionState)
        {
            ConnectButton.IsEnabled = connectionState == ConnectionState.Disconnected;
            ConnectButton.Visibility = connectionState == ConnectionState.Connected ? Visibility.Collapsed : Visibility.Visible;
            ServerModify.IsEnabled = connectionState == ConnectionState.Disconnected;
        }

        protected void OnStartConnection(ServerConnectInfo connectInfo)
        {
            if (StartConnection == null)
                return;

            StartConnection(this, new ConnectEventArgs(connectInfo));
        }

        private void ConnectButton_Click(object sender, RoutedEventArgs e)
        {
            ServerConnectInfo connectInfo = ServerModify.ValidateUserInterface();

            if (connectInfo != null)
                OnStartConnection(connectInfo);
        }

        private void ServerListBoxContextMenu_Opened(object sender, RoutedEventArgs e)
        {
            EditerverContextMenuItem.IsEnabled = ServerListBox.SelectedItem != null;
            RemoveServerContextMenuItem.IsEnabled = ServerListBox.SelectedItem != null;
            ConnectServerContextMenuItem.IsEnabled = ServerListBox.SelectedItem != null;
        }

        private void AddServerContextMenuItem_Click(object sender, RoutedEventArgs e)
        {
            ServerModifyWindow createWindow = new ServerModifyWindow();
            createWindow.Init();
            
            if (createWindow.ShowDialog() == true)
                ServerListBox.Items.Add(new ServerListBoxEntry { Name = createWindow.ServerName, ConnectInfo = createWindow.ConnectInfo});

            createWindow.Close();
        }

        private void EditerverContextMenuItem_Click(object sender, RoutedEventArgs e)
        {
            ServerListBoxEntry currentEntry = (ServerListBoxEntry)ServerListBox.SelectedItem;
            int currentEntryPosition = ServerListBox.SelectedIndex;

            ServerModifyWindow editWindow = new ServerModifyWindow();
            editWindow.Init(currentEntry.Name, currentEntry.ConnectInfo);            

            if (editWindow.ShowDialog() == true)
            {
                ServerListBox.Items.RemoveAt(currentEntryPosition);
                ServerListBox.Items.Insert(currentEntryPosition, new ServerListBoxEntry { Name = editWindow.ServerName, ConnectInfo = editWindow.ConnectInfo });
            }

            editWindow.Close();
        }

        private void RemoveServerContextMenuItem_Click(object sender, RoutedEventArgs e)
        {
            ServerListBox.Items.RemoveAt(ServerListBox.SelectedIndex);
        }

        private void Application_Exit(object sender, ExitEventArgs e)
        {
            SaveServerList();
        }

        private void ConnectionAreaControl_Loaded(object sender, RoutedEventArgs e)
        {
            LoadServerList();
        }

        private void LoadServerList()
        {
            if (!File.Exists(Application.ServerListFilePath))
                return;

            XDocument doc = XDocument.Load(Application.ServerListFilePath);

            foreach (XElement serverElement in doc.Root.Elements("Server"))
            {
                ServerListBox.Items.Add(ServerListBoxEntry.ReadFromXElement(serverElement));
            }
        }

        private void SaveServerList()
        {
            Application.EnsureSettingsFolderExists();

            if (File.Exists(Application.ServerListFilePath))
                File.Delete(Application.ServerListFilePath);

            XDocument doc = new XDocument(new XElement("Servers"));

            foreach (ServerListBoxEntry entry in ServerListBox.Items)
            {
                XElement serverElement = new XElement("Server");
                entry.WriteToXElement(serverElement);
                doc.Root.Add(serverElement);
            }

            doc.Save(Application.ServerListFilePath);
        }

        private void ConnectServerContextMenuItem_Click(object sender, RoutedEventArgs e)
        {
            ServerListBoxEntry currentEntry = (ServerListBoxEntry)ServerListBox.SelectedItem;
            OnStartConnection(currentEntry.ConnectInfo);
        }

        private void ServerListBox_MouseDoubleClick(object sender, System.Windows.Input.MouseButtonEventArgs e)
        {
            ServerListBoxEntry currentEntry = (ServerListBoxEntry)ServerListBox.SelectedItem;

            if (currentEntry == null)
                return;

            OnStartConnection(currentEntry.ConnectInfo);
        }
    }
}
